<?php

class FormAction_Index extends FormAction
{

  public $limit = 10;

  public $sortField;

  public $sortDirection;

  protected $action = Form::ACTION_INDEX;

  protected $pager;

  public function execute()
  {
    $this->loadData();
  }

  public function render()
  {
    $elements = $this->form->getElements($this->action);

    $groups = array();
    $groups[] = array(1, '&nbsp;');
    $group = array(0, '&nbsp;');

    while ($element = $elements->next()) {
      if ($element instanceof FormGroup) {
        if ($group[0]) {
          $groups[] = $group;
        }

        $group = array(0, $element->getTitle());

        $_elements = $element->getElements($this->action);

        while ($_element = $_elements->next()) {
          $group[0]++;
        }

        $this->set('has_groups', true);

        $groups[] = $group;

        $group = array(0, '&nbsp;');
      }
      else {
        $group[0]++;
      }
    }

    if ($group[0]) {
      $groups[] = $group;
    }

    $groups[] = array(1, '&nbsp;');

    $this->set('pager', $this->pager);
    $this->set('groups', $groups);

    return parent::render();
  }

  protected function loadData()
  {
    $params = array();

    $params['fields'] = array($this->form->pk);
    $params['where'] = array();
    $params['data'] = array();

    foreach ($this->form->getFilters() as $filter) {
      $filter->injectQueryParams($params);
    }

    $elements = $this->form->getElements($this->action);
    while ($element = $elements->next()) {
      $element->injectQueryParams($params);
    }

    $params['fields'] = array_filter(array_unique($params['fields']));
    $params['limit'] = $this->getLimit();
    $params['offset'] = $this->getOffset();

    $row = $this->gateway()->findAll($params);

    $this->filterDbData($row, $this->action);

    $this->formData = $row;

    $this->pager = $this->gateway()->findPager($params);
  }

  protected function getOffset()
  {
    return s::request()->get('offset');
  }

  protected function getLimit()
  {
    return $this->limit;
  }

}
